<template>
  <div class="list-content inspect-record-list">
    <div>
      <el-row type="flex" justify="space-between">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent>
          <el-form-item>
            <el-select
              class="none-right-bd"
              @change="getData(1)"
              v-model="formInline.queryTimeType"
              style="width:120px;"
            >
              <el-option label="按开始时间" value="1"></el-option>
              <el-option label="按结束时间" value="2"></el-option>
            </el-select>
            <el-date-picker
              class="none-left-bd"
              v-model="formInline.time"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="util.intTimePickerOptions()"
              @change="getData(1)"
              style="width:280px;"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-select
              clearable
              placeholder="全部状态"
              @change="getData(1)"
              v-model="formInline.status"
              style="width:120px;"
            >
              <el-option label="执行中" :value="1"></el-option>
              <el-option label="已结束" :value="2"></el-option>
              <el-option label="待领取" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              filterable
              clearable
              placeholder="全部标签"
              @change="getData(1)"
              v-model="formInline.labelId"
              style="width:140px;"
            >
              <el-option v-for="item in labelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item v-if="isMuilUnitUser">
            <el-select
              v-model="formInline.orgIds"
              placeholder="全部业主单位"
              filterable
              :collapse-tags="true"
              @change="handleOrgChange"
            >
              <el-option
                v-for="item in orgOptionsAll"
                :key="item.organizationId"
                :label="item.shortName"
                :value="item.organizationId"
              ></el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item>
            <el-select v-model="formInline.planId" placeholder="全部计划" filterable clearable @change="getData(1)">
              <el-option v-for="item in planList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select v-model="formInline.userIds" placeholder="责任人" filterable clearable @change="getData(1)">
              <el-option v-for="item in userList" :key="item.accountName" :label="item.name" :value="item.accountName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="formInline.queryContent"
              placeholder="任务名称"
              @keyup.enter.native="getData(1)"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="form-search-btn" type="primary" @click="getData(1)">查询</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row v-loading="loading" class="overclick-wrap" :gutter="40" type="flex" justify="space-between">
        <el-col :span="6">
          <div class="item-wrap" @click="formInline.result=''" :class="{active:formInline.result==''}">
            <div class="item-content">
              <p class="item-value color-4">{{ staticObj.total }}</p>
              <p class="item-title bold">任务总数</p>
              <p class="item-title">累计点位{{ staticObj.pointNum }}</p>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="item-wrap" @click="formInline.result='2'" :class="{active:formInline.result==2}">
            <div class="item-content">
              <p class="item-value color-3">{{ staticObj.examinedNum}}</p>
              <p class="item-title bold">完成数</p>
              <p class="item-title">完成率 {{finishRate}}%</p>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="item-wrap" @click="formInline.result='1'" :class="{active:formInline.result==1}">
            <div class="item-content">
              <p class="item-value color-1">{{ staticObj.unExaminedNum }}</p>
              <p class="item-title bold">未完成数</p>
              <p class="item-title">未完成率 {{unfinishRate}}%</p>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="item-wrap" @click="formInline.result=-1" :class="{active:formInline.result==-1}">
            <div class="item-content">
              <p class="item-value color-2">{{ staticObj.unIsOkNum }}</p>
              <p class="item-title bold">有发现不合格点位的任务数</p>
              <p class="item-title">合计发现不合格点位 {{staticObj.noOkPointNum}}个</p>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-table
        v-show="formInline.currentPageTotal>0"
        v-loading="loading"
        :data="tableData"
        ref="mainTable"
        style="width: 100%"
      >
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column prop="name" label="任务名称" header-align="center" min-width="200px">
          <template slot-scope="scope">
            <p style="margin-left: 10px;">
              {{ scope.row.name }}
              <el-link
                v-if="scope.row.approvePicUrl"
                class="trusted-time"
                @click="openTrustedTimeDialog(scope.row.approvePicUrl, scope.row.certificateUrl)"
              >已通过可信时间认证</el-link>
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="90">
          <template slot-scope="scope">
            <el-tag
              :type="['','primary','success','info'][scope.row.status]"
              disable-transitions
            >{{['','执行中','已结束','待领取'][scope.row.status]}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标签" prop="labelName" min-width="100px"></el-table-column>
        <el-table-column label="时限" width="300" align="center">
          <template v-slot="sc">{{sc.row.startTime.substr(0,16)}}~{{sc.row.endTime.substr(0,16)}}</template>
        </el-table-column>
        <el-table-column prop="lliablepersonsName" label="责任人" min-width="150px"></el-table-column>
        <el-table-column prop label="包含点位数" width="100" align="center">
          <template v-slot="sc">{{sc.row.pointIds?sc.row.pointIds.split(',').length:0}}</template>
        </el-table-column>
        <el-table-column prop label="完成度" width="120" align="center">
          <template v-slot="sc">
            <el-progress
              :text-inside="true"
              :stroke-width="22"
              :percentage="Math.ceil(sc.row.examined*100/(sc.row.pointIds?sc.row.pointIds.split(',').length:1))"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="unIsOkNum" label="发现不合格点位数" width="160" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="70">
          <template slot-scope="scope">
            <el-button @click="showDetail(scope.$index, scope.row)" type="text" size="small">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="formInline.currentPageTotal>0"
        background
        @size-change="sizeChange"
        @current-change="pageChange"
        :current-page="formInline.currentPageIndex"
        :page-sizes="[10, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="formInline.currentPageTotal"
      ></el-pagination>
      <div v-show="showEmpty&&formInline.currentPageTotal==0" class="text-center">
        <img
          src="../../assets/images/inspect/no-record.png"
          style="margin-top:calc(50vh - 422px);width:600px;height:424px;"
        />
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="可信时间认证"
      width="600px"
      v-if="trustedTimeDialog"
      :visible.sync="trustedTimeDialog"
      @close="trustedTimeDialog = false"
      v-dialogDrag
    >
      <trusted-time :info="trustedTimeInfo"></trusted-time>
    </el-dialog>
    <inspect-detail
      ref="InspectDetail"
      v-if="detailVisible"
      :formatPicUrl="formatPicUrl"
      @goTroubleDetail="goTroubleDetail"
    ></inspect-detail>
    <trouble-detail ref="TroubleDetail" v-if="showTroubleDetail" />
  </div>
</template>

<style lang="scss">
.inspect-record-list {
  .none-right-bd {
    .el-input__inner {
      border-right: none;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }
  }
  .item-title {
    &.bold {
      font-weight: bold;
      color: #333;
    }
  }
}
</style>

<script>
import util from '@/utils/util'
import TrustedTime from '../Police/Dialog/TrustedTime'
import { getUsers } from '@/api/api'
import {
  getInspectTaskListForClient,
  getInspectTaskStatistic,
  getInspectPlanList,
  getPointLabelList,
} from '@/api/inspectx'
import { mapState, mapGetters, mapMutations } from 'vuex'
import InspectDetail from './Dialog/InspectRecordDetail'
import TroubleDetail from '../HiddenDangerRectification/hiddenTroubleDetail.vue'

export default {
  name: 'InspectRecord',
  props: ['param'],
  components: {
    TrustedTime,
    InspectDetail,
    TroubleDetail,
  },
  data() {
    return {
      showEmpty: false,
      formInline: {
        userIds: '',
        queryTimeType: '1',
        queryContent: '',
        result: '',
        orgIds: '',
        time: '',
        currentPageSize: 10,
        currentPageIndex: 1,
        currentPageTotal: 0,
        status: '',
        labelId: '',
        planId: '',
      },
      util: util,
      tableData: [], //表格数据
      staticObj: {
        unIsOkNum: 0, //有不合格点位的任务数
        total: 0, //总的任务数（分页用这个total）
        examinedNum: 0, //已完成的任务数
        unExaminedNum: 0, //未完成的任务数
        noOkPointNum: 0, //不合格点位数（两次任务中，同一个点位不合格算两次）
      }, //头部各状态个数统计
      loading: false,
      trustedTimeDialog: false, // 可信时间弹框
      trustedTimeInfo: {},
      userList: [],
      detailVisible: false,
      planList: [],
      labelList: [],
      showTroubleDetail: false,
    }
  },
  computed: {
    ...mapState(['orgOptions', 'refreshInspectTask']),
    ...mapGetters([
      'isMuilUnitUser',
      'orgOptionsAll',
      'userOrgId',
      'userOrgIds',
      'userFullOrgIds',
    ]),
    finishRate() {
      return Math.round(
        (this.staticObj.examinedNum * 100) /
          (this.staticObj.examinedNum + this.staticObj.unExaminedNum || 1)
      )
    },
    unfinishRate() {
      return Math.round(
        (this.staticObj.unExaminedNum * 100) /
          (this.staticObj.examinedNum + this.staticObj.unExaminedNum || 1)
      )
    },
  },
  created: function () {
    this.formInline.orgIds = this.isMuilUnitUser
      ? this.userOrgIds
      : this.userOrgId
    this.getPointLabelList()
    this.getUserList()
    this.getPlanList()
  },
  activated() {
    if (this.refreshInspectTask) {
      let { account, result, queryTimeType, time, planId, labelId, status } =
        this.$route.params
      this.formInline.userIds = account
      this.formInline.queryTimeType = queryTimeType
      this.formInline.time = time
      this.formInline.planId = planId
      this.formInline.labelId = labelId
      this.formInline.status = status
      if (this.formInline.result != result) {
        // 会触发列表刷新
        this.formInline.result = result
      } else {
        this.getData(1)
      }
      this.getStatistic()
    } else {
      this.getData(1)
      this.getStatistic()
    }
    this.setRefreshInspectTask(false)
  },
  methods: {
    goTroubleDetail(id) {
      this.showTroubleDetail = true
      this.$nextTick(() => {
        this.$refs.TroubleDetail.init(id)
      })
    },
    ...mapMutations(['setRefreshInspectTask']),
    getData(_pageIndex) {
      this.getList(_pageIndex)
      this.getStatistic()
    },
    //获取列表
    getList(_pageIndex) {
      if (_pageIndex) {
        this.formInline.currentPageIndex = _pageIndex
      }
      this.loading = true
      let {
        currentPageIndex,
        currentPageSize,
        queryContent,
        status,
        labelId,
        queryTimeType,
        time,
        planId,
        result,
        userIds,
      } = this.formInline
      getInspectTaskListForClient({
        queryType: 1,
        pageIndex: currentPageIndex - 1,
        pageSize: currentPageSize,
        queryContent,
        orgIds: this.userFullOrgIds,
        status: status,
        labelId: labelId,
        startTime: time ? time[0] + ' 00:00:00' : '',
        endTime: time ? time[1].substr(0, 10) + ' 23:59:59' : '',
        planId,
        result: result > 0 ? result : '',
        queryTimeType,
        lliablepersons: userIds,
        pointResult: result == -1 ? 2 : '',
      }).then((result) => {
        this.formInline.currentPageTotal = result.total
        this.tableData = result.data || []
        this.loading = false
        this.showEmpty = true
      })
    },
    // 统计
    getStatistic() {
      let {
        queryContent,
        status,
        labelId,
        queryTimeType,
        time,
        planId,
        userIds,
      } = this.formInline
      getInspectTaskStatistic({
        queryContent,
        orgIds: this.userFullOrgIds,
        status: status,
        labelId: labelId,
        startTime: time ? time[0] + ' 00:00:00' : '',
        endTime: time ? time[1].substr(0, 10) + ' 23:59:59' : '',
        planId,
        queryTimeType,
        lliablepersons: userIds,
      }).then((result) => {
        this.staticObj = result.data
      })
    },
    getPointLabelList() {
      getPointLabelList({ type: 1 }).then((res) => {
        this.labelList = res.data || []
      })
    },
    // 计划列表
    getPlanList() {
      getInspectPlanList({
        queryType: 0,
        orgIds: this.userFullOrgIds,
      }).then((result) => {
        this.planList = result.data
        this.loadingPlanList = false
      })
    },
    // 责任人列表
    getUserList() {
      getUsers({
        queryType: 0,
        orgIds: this.formInline.orgIds,
      }).then((res) => {
        this.userList = res.data
        this.loadingUserList = false
      })
    },
    sortChange(obj) {
      if (obj.order) {
        this.formInline.order = obj.order == 'descending' ? 'desc' : 'asc'
        this.formInline.orderByPro = obj.prop
        this.getList(1)
      }
    },
    formatPicUrl(val) {
      if (val.indexOf('imageView2') > -1) return val
      if (
        val.indexOf('://file.kshqfire.com') < 0 &&
        val.indexOf('://file.yx-ilink.com') < 0
      )
        return val + '?w=192&h=108'
      if (val.indexOf('imageView2') < 0)
        return val + '?imageView2/2/w/192/h/108/q/75'
      return val
    },
    handleOrgChange() {
      this.userList = []
      this.formInline.userIds = ''
      this.planList = []
      this.formInline.planId = ''
      this.getUserList()
      this.getPlanList()
      this.getList(1)
    },
    // 打开可信时间弹框
    openTrustedTimeDialog(picUrl, fileUrl) {
      if (picUrl) {
        this.trustedTimeInfo = {
          picUrl: picUrl,
          fileUrl: fileUrl,
        }
      } else {
        this.trustedTimeInfo = {}
      }
      this.trustedTimeDialog = true
    },
    showDetail(index, row) {
      this.detailVisible = true
      this.$nextTick(() => {
        this.$refs.InspectDetail.init(row)
      })
    },
    sizeChange(val) {
      //页码切换
      this.formInline.currentPageIndex = 1
      this.formInline.currentPageSize = val
      this.getList()
    },
    pageChange(val) {
      //翻页
      this.formInline.currentPageIndex = val
      this.getList()
    },
  },
  watch: {
    'formInline.result'(val, oldVal) {
      if (val !== oldVal) {
        this.getList(1)
      }
    },
  },
}
</script>